package com.abel.bigwater.dataserver.model.qdies

import com.abel.bigwater.dataserver.model.PacketCmdException
import io.netty.buffer.ByteBuf
import java.net.Inet4Address
import java.net.InetSocketAddress

/**
 * 读取通信IP地址及端口号（ 即主站的IP地址及端口号）
上位机发送： 帧头 地址 0x07 0x00 校验 帧尾
D10应答： 帧头 地址 0x07 0x06 IP地址4个字节 端口号2个字节 校验 帧尾
 */
open class DtenAskIpPortData(_len: Int) : D10BaseData(_len) {
    companion object {
        const val MIN_LEN = 6
    }

    override var type = FuncType.AskIpPort

    var address: InetSocketAddress? = null

    override fun fill(buf: ByteBuf) {
        buf.writeBytes(address!!.address.address)
        buf.writeShort(address!!.port)
    }

    override fun parse(buf: ByteBuf): Boolean {
        if (buf.readableBytes() < MIN_LEN) throw PacketCmdException("should contain address:port")

        buf.duplicate().apply {
            val ip = Inet4Address.getByAddress(ByteArray(4).also { readBytes(it) })
            val port = readUnsignedShort()

            address = InetSocketAddress(ip, port)
        }

        buf.skipBytes(MIN_LEN)

        return true
    }

    override fun count(): Int = MIN_LEN
}